package com.xxz.terminal;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ContentView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

public class SecondFragment extends Fragment implements Runnable {

    private static final String TAG = "fragment2";
    View contentview;
    TextView textView1,textView2;
    EditText Review_text;
    ImageButton review_button;
    ImageButton list;
    ImageButton next;
    RadioGroup radioGroup;
    String wz = "https://v1.hitokoto.cn?c=i";//用来保存网址
    Handler handler;
    String v[];//用来保存从接口上获得的内容，以便回传主线程
    int flag =0;//定义一个flag用来判断是否改变喜欢按钮的颜色
    DBHelper dbHelper;
    SQLiteDatabase db;
    SharedPreferences sp;
    String user_id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        contentview =  inflater.inflate(R.layout.fragment_second, container, false);
        sp = getActivity().getSharedPreferences("userinformation", Context.MODE_PRIVATE);
        user_id = sp.getString("user_id",null);

        radioGroup = contentview.findViewById(R.id.rdg);//绑定radiobutton
        textView1 = contentview.findViewById(R.id.jd);
        textView2 = contentview.findViewById(R.id.ly);
        Review_text = contentview.findViewById(R.id.review_text);
        Review_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
                int lines = Review_text.getLineCount();
                // 限制最大输入行数
                if (lines > 2) {
                    String str = s.toString();
                    int cursorStart = Review_text.getSelectionStart();
                    int cursorEnd = Review_text.getSelectionEnd();
                    if (cursorStart == cursorEnd && cursorStart < str.length() && cursorStart >= 1) {
                        str = str.substring(0, cursorStart - 1) + str.substring(cursorStart);
                    } else {
                        str = str.substring(0, s.length() - 1);
                    }
                    // setText会触发afterTextChanged的递归
                    Review_text.setText(str);
                    // setSelection用的索引不能使用str.length()否则会越界
                    Review_text.setSelection(Review_text.getText().length());
                    Toast.makeText(getActivity(), "输入内容不能超过2行", Toast.LENGTH_SHORT).show();
                }
            }
        });////设置页面2文本框的最大输入行数

        review_button = contentview.findViewById(R.id.review_button);
        //刚打开界面时也要展示一条句子
        Thread t1 = new Thread(this);//同一个Thread不能重复调用start
        t1.start();

        //为radiobutton设置监听，依据监听返回对应的接口网址,并开启子线程
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.dm) {

                    wz = "https://v1.hitokoto.cn?c=a&c=b";
                    Thread t1 = new Thread(SecondFragment.this::run);
                    t1.start();

                 }
                else if(checkedId == R.id.game) {

                    wz = "https://v1.hitokoto.cn?c=c";
                    Thread t2 = new Thread(SecondFragment.this::run);
                    t2.start();

                    }
                else if(checkedId == R.id.wx) {

                    wz = "https://v1.hitokoto.cn?c=d";
                    Thread t3 = new Thread(SecondFragment.this::run);
                    t3.start();
                    }
                else if(checkedId == R.id.pm) {

                    wz = "https://v1.hitokoto.cn?c=i";
                    Thread t4 = new Thread(SecondFragment.this::run);
                    t4.start();

                    }
                else if(checkedId == R.id.zx) {

                    wz = "https://v1.hitokoto.cn?c=k";
                    Thread t5 = new Thread(SecondFragment.this::run);
                    t5.start();

                    }
                else if(checkedId == R.id.ys) {

                    wz = "https://v1.hitokoto.cn?c=h";
                    Thread t6 = new Thread(SecondFragment.this::run);
                    t6.start();

                    }
                else if(checkedId == R.id.wyy) {

                    wz = "https://v1.hitokoto.cn?c=j";
                    Thread t7 = new Thread(SecondFragment.this::run);
                    t7.start();

                    }

                else if(checkedId == R.id.hh) {

                    wz = "https://v1.hitokoto.cn?c=a&c=b&c=c&c=d&c=e&c=f&c=g&c=h&c=i&c=j&c=k&c=l";
                    Thread t8 = new Thread(SecondFragment.this::run);
                    t8.start();
                }
            }
        });

        next = contentview.findViewById(R.id.next);//绑定按钮上一条
        list = contentview.findViewById(R.id.list);//绑定按钮list

//三个按钮的事件处理
        review_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String review_text = Review_text.getText().toString();
                //编辑框为空则提示
                if(review_text.isEmpty()){

                    Toast.makeText(getActivity(), "写点什么再保存吧!o(*￣▽￣*)ブ", Toast.LENGTH_SHORT).show();

                }
                else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示").setMessage("一字千金,要留下它们吗").setPositiveButton("是",new DialogInterface.OnClickListener(){

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //保存编辑框中的内容并存入数据库
                            dbHelper = new DBHelper(getActivity());
                            db = dbHelper.getWritableDatabase();

                            String content = textView1.getText().toString();//获得句子
                            String source = textView2.getText().toString();//获得出处

                            LocalDateTime localDateTime = LocalDateTime.now();
                            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//用format标准化时间形式
                            String datetime = localDateTime.format(dtf);

                            ContentValues contentValues  =new ContentValues();
                            contentValues.put("sentence",content);
                            contentValues.put("source",source);
                            contentValues.put("user_id",user_id);
                            contentValues.put("date",datetime);
                            contentValues.put("review_text",review_text);

                            db.insert("sentence_data",null,contentValues);
                            //已经收藏起来了,有时间就去回味一下吧,收藏成功的提示
                            Toast.makeText(getActivity(), "已经收藏起来了,有时间就去回味一下吧", Toast.LENGTH_SHORT).show();
                            Review_text.setText(null);
                        }
                    }).setNegativeButton("否",null);
                    builder.create().show();
                }
            }
        });

        //此处使用了自定义类防止按钮被过快点击
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                Thread t = new Thread(SecondFragment.this::run);
                t.start();
            }
        });

        //打开句子收藏展示页面
        list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),SentenceCollectionActivity.class);
                startActivity(intent);
            }
        });

        //用handler处理回传的值并显示
        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(Message msg) {

                if(msg.what==7){

                    String[] str = (String[]) msg.obj;
//                    Toast.makeText(getActivity(), str[1], Toast.LENGTH_SHORT).show();
                    String jz = str[0];//取出句子
                    String ly = str[1];//取出出处
                    String type = str[2];//取出类型
                    Log.i(TAG, "handleMessage: getMessage msg = " + str);
                    textView1.setText(jz);
                    textView2.setText(ly);

                }
                super.handleMessage(msg);
            }
        };
        return contentview;
    }

    //子线程获取”一言“接口数据
    @Override
    public void run() {

        Log.i("run", "run: run()......");
        String content = new String();
        String value1 = new String();//用于存储句子内容字段
        String value2 = new String();//用于存储句子的来源字段
        String value3 = new String();//用于存储句子类型

        URL url = null;
        try {

            url = new URL(wz);//“一言”的网址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//与该网址建立联系
            connection.setRequestMethod("GET");//设置访问方式
            connection.connect();//建立连接

            int responsecode = connection.getResponseCode();
            Log.i("re","response"+responsecode);

            if(responsecode == HttpURLConnection.HTTP_OK){

                InputStream in = connection.getInputStream();//获取数据流

                InputStreamToString convert = new InputStreamToString();
                content = convert.InputStreamToString(in);//调用InputStreamToString方法将数据流转化为字符串
                Log.i(TAG,"run: content"+content);

                JSONObject jsonObject = new JSONObject(content);//将得到的字符串转化为JSONObject类型以方便通过接口定义的“hitokoto”字段名直接取出正文
                value1 = jsonObject.optString("hitokoto");//取出正文即句子将其转化为字符串
                value2 = jsonObject.optString("from");//取出出处
                value3 = jsonObject.optString("type");
                Log.i("value","value"+value1+value2+value3);
            }
            v= new String[]{value1, value2,value3}; //将正文与出处存入数组

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }

        //获取Msg对象，用于返回主线程
        Message msg = handler.obtainMessage(7,v);
        handler.sendMessage(msg);
        Log.i(TAG, "run: sendMessage ok");
    }
}
